package cn.tedu.spring;

import cn.tedu.spring.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;

/**
 * Author：程Sir
 * Name： framework
 * Content:
 */
@Configuration
@ComponentScan("cn.tedu.spring")
@EnableWebMvc
public class SpringMvcConfig implements WebMvcConfigurer {

    /*
        该方法是给springMVC指定拦截器，也就是进行拦截器的注册！
        与此同时，也可以进行拦截请求的注册！
        需要注意的是，1个路径都没有配置时，是拦截所有！
                   在配置了拦截路径之后，没有被配置的路径是默认放行的！
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        System.out.println("init Interceptor");
        // 先创建拦截器对象
        LoginInterceptor loginInterceptor = new LoginInterceptor();
        // 注册拦截器
        registry.addInterceptor(loginInterceptor)
                // 拦截/p/路径下的所有请求，需要注意的是，只能够拦截一级，当需要拦截/p/路径下的所有级时，可以使用 **
                .addPathPatterns("/p/**")
                // 配置需要直接放行的路径！【一般被称之为"白名单"】
                .excludePathPatterns("/p/login.do","/p/register.do");
    }



    private String characterEncoding = "utf-8";

    @Bean
    public ViewResolver configViewResolver() {
        System.out.println("init ThymeleafViewResolver");

        //设置模板保存位置为 /resources/templates/*.html
        ClassLoaderTemplateResolver templateResolver =
                new ClassLoaderTemplateResolver();
        //模版存储文件夹
        templateResolver.setPrefix("/templates/");
        //模版后缀
        templateResolver.setSuffix(".html");
        templateResolver.setCharacterEncoding("UTF-8");
        templateResolver.setTemplateMode(TemplateMode.HTML);
        templateResolver.setCacheable(false);
        //创建模板引擎
        SpringTemplateEngine templateEngine =
                new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);
        templateEngine.setEnableSpringELCompiler(true);
        //创建模版解析器
        ThymeleafViewResolver viewResolver =
                new ThymeleafViewResolver();
        viewResolver.setCharacterEncoding("UTF-8");
        viewResolver.setTemplateEngine(templateEngine);
        return viewResolver;
    }
}
